<template>
	<view class="detail">
		<view class="bgheader pt-3">
			<view class="Info mx-3 p-3">
				<view class="left">
					<image v-if="itemData?.logo" :src="showImage(itemData?.logo[0]?.storageKey)" mode="aspectFill"
						class="img">
					</image>
					<image class="img" src="../../uni_modules/lime-empty/static/default.png" mode="aspectFit"></image>
					<view class="type ml-1 font-small mt-1">{{orgDetail.organizationType}}</view>
				</view>
				<view class="right ml-3">
					<view style="font-size: 35rpx;">{{itemData.organizationName}}</view>
					<view class=""><uni-rate v-model="orgDetail.starRating" @change="onChange" size="14" max="5" />
					</view>
					<view class="font-small text-default" v-for="(item,index) in itemData.formId" :key="item">
						<span v-if="item.title=='队长'">队长-{{item.nameName}}</span>
					</view>
					<view class="slogan font-small mt-2">
						<text class="text">{{itemData.slogan || '-'}}</text>
					</view>
					<view class="mt-1 font-small">
						<text>人数： {{orgDetail.currentNumber || '-'}}</text> <text class="pl-1 ml-3">活动时数：
							{{orgDetail.activityDuration}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="introduction p-3">
			<view class="font-weight-bold h4 mb-2 title">组织简介</view>
			<view class="textInfo text-default" v-if="itemData.briefIntroduction" v-html="itemData.briefIntroduction">
			</view>
			<view class="textInfo text-default" v-else>
				本活动由组织方发起，并已承诺该活动为非营利性活动。平台方未委托授权任何公司或个人收取手续费、
				服务费等各类费用，请勿轻信非官方渠道的虚假信息，谨防您的利益受损，如有疑问可拨打客服电话xxx-xxx-xxx进行咨询
			</view>
		</view>
		<view class="requirements mt-3 p-3">
			<view class="font-weight-bold h4 mb-2 title">组织要求</view>
			<view class="textInfo text-default" v-html="itemData.requirements">
			</view>

		</view>
		<view class="volunteerList mt-3 p-3">
			<view class="h4 ">组织成员列表<text class="num " v-if="itemData.formId?.length"> 已有成员( <text
						class="organizationNum font-weight-bold">{{itemData.formId.length}}</text> )人</text></view>
			<view class="person_img mt-3">
				<view class="item flex flex-column align-center" v-for="(item,index) in showOrgData" :key="item">
					<view class="item_img flex justify-center align-center"
						:style="{'backgroundColor':addBgColorList[index]}">
						<view class="name">{{item.nameName.slice(0,1)}}</view>
					</view>
					<view class="name mt-1">{{item.nameName}}</view>
					<view v-if="item.title">({{item.title}})</view>
				</view>
			</view>

			<LoadingMore :viewMorestatus="viewMorestatus" :viewNum='viewNum' @viewMore="viewMore"></LoadingMore>

		</view>

		<view class="Application">
			<view class="btn" :class="{'expire-btn':isAlearyOrg}" @click="toggle('center')">
				<view class="font-weight-bold">{{isAlearyOrg ? '已加入': '申请加入组织'}}</view>
			</view>
		</view>
		<uni-popup class="popup-box" ref="popup" background-color="#fff">
			<view class="popup-content p-3">
				<view class="title text-center font-weight-bold">加入组织</view>
				<form @submit="formSubmit" @reset="formReset">
					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title  font-sm ">组织</view>
						<input class="uni-input border pl-2 py-1 font-sm" name="organization" placeholder="请输入"
							:value="formData.team.organization" disabled="" />
					</view>

					<view class="uni-form-item uni-column mt-1">
						<view class="label form_title   font-sm">姓名</view>
						<input class="uni-input border pl-2 py-1 font-sm" name="name" placeholder="请输入"
							:value="formData.name" disabled="" />

					</view>
					<view class="flex mt-1" style="gap: 30rpx;">
						<view class="uni-form-item uni-column flex-1">

							<view class="label form_title require font-sm">生日日期</view>



							<uni-datetime-picker type="date" placeholder="请选择" name="birthday" v-model="dateTime"
								@change="DateChange" />

						</view>
						<view class="uni-form-item uni-column flex-1">
							<view class="label form_title font-sm require">性别</view>
							<uni-data-select name="sex" class="uni-input1 select border pl-2 py-1 font-sm"
								style="height: 70rpx;" v-model="sex" :localdata="sexRange"
								:clear="false"></uni-data-select>
						</view>
					</view>
					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title font-sm">部门</view>

						<input class="uni-input border pl-2 py-1 font-sm" name="department" placeholder="请输入"
							:value="formData.department" disabled />
					</view>
					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title font-sm">工号</view>
						<input class="uni-input border pl-2 py-1 font-sm" name="username" placeholder="请输入"
							:value="formData.username" disabled />
					</view>
					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title font-sm require">联系方式</view>
						<input class="uni-input1 border pl-2 py-1 font-sm" name="contactInformation" placeholder="请输入"
							:value="formData.contactInformation" />
					</view>
					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title font-sm require">健康状况</view>
						<uni-data-select class="uni-input1 border select pl-2 py-1 font-sm" style="height: 70rpx;"
							v-model="condition" :localdata="conditionRange" :clear="false"></uni-data-select>
					</view>

					<view class="uni-form-item uni-column  mt-1">
						<view class="label form_title font-sm require">专业特长</view>
						<input class="uni-input1 border pl-2 py-1 font-sm" name="speciality" placeholder="请输入"
							:value="formData.speciality" />

					</view>
					<view class="uni-btn-v">
						<button form-type="submit" class="btn font-weight-bold">提交</button>
					</view>
				</form>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		showImage
	} from '../../api/common.js'
	import {
		getDictData,
		formatterDictData,
		getRandomHexColor
	} from '../../common/common.js'
	import request from '../../api/index.js'
	import LoadingMore from '../../component/LoadingMore/LoadingMore.vue';
	import {
		useUserStore
	} from '@/stores/user.js'

	const showClearIcon = ref(true)



	const userStore = useUserStore()
	const type = ref('')
	const popup = ref(0)

	const value = ref(3)
	const itemData = ref({})
	const addBgColorList = ref([])
	const userData = reactive({})
	const isAlearyOrg = ref('')
	const dateTime = ref(false)
	const sex = ref('')
	const condition = ref('')
	const orgDetail = ref({})
	const itemjsId = ref('')
	const sexRange = ref([{
			value: '0',
			text: "男"
		},
		{
			value: '1',
			text: "女"
		},

	])
	const conditionRange = ref([])
	const personAge = ref(null)
	const formData = ref({

		team: {
			organization: '',
			teamjsId: '',
		},
		name: '', //姓名
		username: '', //工号
		birthday: '',
		sex: '',
		department: '', //部门
		userId: '', //用户id
		contactInformation: "", //联系方式
		condition: '', //健康情况
		speciality: '' //专业特长
	})


	const requireList = ref([{
			text: '请输入生日日期',
			key: 'dateTime'
		},
		{
			text: '请输入联系方式',
			key: 'contactInformation'
		},
		{
			text: '请输入专业特长',
			key: 'speciality'
		},
		{
			text: '请选择身体状况',
			key: 'condition'
		},
		{
			text: '请选择性别',
			key: 'sex'
		},
	])

	const viewMorestatus = ref('more')
	const viewNum = ref(10)
	const showOrgData = ref([])


	onLoad((options) => {
		console.log("options--------", options)
		const itemId = JSON.parse(options.id)
		const itemData = JSON.parse(options.itemData)
		console.log("itemData----------", itemData)
		itemjsId.value = itemId
		orgDetail.value = itemData
		getOrganizationItemData(itemId)
	})

	const getConditionRange = () => {
		conditionRange.value = getDictData('DIC003')
	}

	const clearInput = (event) => {
		personAge.value = event.detail.value;
		if (event.detail.value.length > 0) {
			showClearIcon.value = true;
		} else {
			showClearIcon.value = false;
		}
	}
	const clearIcon = () => {
		personAge.value = null;
		showClearIcon.value = false;
	}


	const addBgColor = (length) => {

		let colorsList = []
		uni.getStorage({
			key: 'colorsList',
			success(e) {
				console.log("colorsList------", e.data)
				colorsList = e.data
			},

		});
		for (let i = 0; i < length; i++) {
			let bgColor = colorsList[i]
			console.log("bgColor----------", bgColor)
			addBgColorList.value.push(bgColor)
		}
		console.log("addBgColorList.value----------", addBgColorList.value)
	}

	const DateChange = (e) => {
		console.log("e---------", e);
		// dateTime.value = e
		formData.value.birthday = e
		console.log("formData.value---------", formData.value);

	}

	const viewMore = () => {
		console.log("查看更多")
		viewMorestatus.value = 'loading'


		let length = itemData.value?.formId?.length;

		if ((length - viewNum.value) < 10) {
			console.log("===============================================================")
			viewNum.value = length

		} else {
			viewNum.value += 10;


		}
		console.log("length-------", length)
		console.log("viewNum.value-------", viewNum.value)
		setTimeout(() => {
			if (length >= viewNum.value) {
				getOrganizationItemData(itemjsId.value)
				viewMorestatus.value = 'more'
			}

			if (length == viewNum.value) {
				viewMorestatus.value = 'noMore'
			}
		}, 1000)
	}


	const getOrganizationItemData = (id) => {
		request({
			url: `/api/volunteer/teamjs/${id}`,
			method: 'GET',
			data: {}
		}, e => {
			if (e.success) {
				uni.getStorage({
					key: 'userData',
					success(e) {
						console.log("colorsList------", e.data)
						userData.value = e.data
					},

				});
				console.log('e-------------', e.data)
				itemData.value = e.data
				itemData.value?.formId.forEach((item) => {
					console.log("item -------============", item);
					if (item.title == '队员') {
						item.title = ''
					}
					if (userData.value?.name == item.nameName) {
						isAlearyOrg.value = true
					}


				})

				// 排序
				itemData.value?.formId.sort((a, b) => {
					// 如果 a 是队长，则应该排在 b 前面（除非 b 也是队长）
					if (a.title === '队长') return b.title === '队长' ? 0 : -1;
					// 如果 b 是队长，则 b 应该排在 a 前面
					if (b.title === '队长') return 1;

					// 如果 a 是管理员，则 a 应该排在没有 title 的 b 前面（除非 b 也是管理员）
					if (a.title === '管理员') return !b.title ? -1 : 0;
					// 如果 b 是管理员，则 b 应该排在没有 title 的 a 前面
					if (b.title === '管理员') return !a.title ? 1 : 0;

					// 如果两者都没有 title，则保持原顺序
					return 0;
				});



				const length = itemData.value?.formId?.length
				if (length < 10) {
					viewMorestatus.value = 'noMore'
				}
				addBgColor(length)

				let showData = itemData.value?.formId?.slice(0, viewNum.value);


				showOrgData.value = showData


			} else {
				uni.showToast({
					title: '获取组织信息失败',
					icon: 'none'
				})
			}
		})
	}


	const applyAdd = () => {
		// api/volunteer/teamjs-bd/teamjs-bd-add
		request({
			url: `/api/volunteer/teamjs-bd/teamjs-bd-add`,
			method: 'POST',
			data: formData.value
		}, e => {
			if (e.success) {
				console.log('e-------------', e)
				uni.showToast({
					title: '申请成功',
					icon: 'error'
				})

			} else {
				uni.showToast({
					title: e.errorMessage,
					icon: 'error'
				})
			}
		})

	}

	const onChange = (e) => {
		console.log('打分', e)
	}


	const fromCheck = (tip) => {
		uni.showToast({
			title: tip,
			icon: 'error'
		})

	}

	const toggle = (type) => {
		console.log("type--------", type)
		// type.value = type
		// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
		if (isAlearyOrg.value) {

			uni.showToast({
				title: '您已加入该组织！',
				icon: 'error'
			})
			return
		}
		popup.value.open(type)
		getConditionRange()
		console.log("itemData.value---------", itemData.value)

		console.log("userStore---------", userData.value)



		formData.value.team.organization = itemData.value.organizationName
		formData.value.username = userData.value.username
		formData.value.contactInformation = userData.value.mobile

		formData.value.condition = userData.value.condition
		condition.value = userData.value.condition

		formData.value.speciality = userData.value.speciality
		dateTime.value = userData.value.birthday
		formData.value.birthday = userData.value.birthday
		console.log("userData?-----", userData.value)
		if (userData.value?.sex == '男') {
			console.log("userData?.sexuserData?.sexuserData?.sexuserData?.sex")
			sex.value = '0'
		} else if (userData.value?.sex == '女') {
			sex.value = '1'
		} else {
			sex.value = '2'
		}

		formData.value.name = userData.value.name
		formData.value.department = userData.value?.departments[0].name

	}
	const formSubmit = (e) => {
		formData.value = e.detail.value
		formData.value.userId = userData.value.id

		formData.value.birthday = dateTime.value
		formData.value.contactInformation = formData.value.contactInformation
		formData.value.condition = condition.value
		formData.value.teamjsId = itemjsId.value



		if (sex.value == '0') {
			formData.value.sex = '男'
		} else if (sex.value == '1') {
			formData.value.sex = '女'
		} else {
			formData.value.sex = '未知'
		}


		if (!dateTime.value) {
			fromCheck(requireList.value[0].text)
			console.log("dateTimedateTimedateTimedateTime")
			return;
		}

		if (!formData.value.contactInformation) {
			console.log("contactInformationcontactInformationcontactInformationcontactInformationcontactInformation")
			fromCheck(requireList.value[1].text)
			return;
		}

		if (!formData.value.speciality) {
			console.log("specialityspecialityspecialityspecialityspecialityspeciality")
			fromCheck(requireList.value[2].text)
			return;
		}

		if (!formData.value.condition) {

			fromCheck(requireList.value[3].text)
			return;
		}

		if (!formData.value.sex) {

			fromCheck(requireList.value[4].text)
			return;
		}


		console.log("formData.value-----", formData.value)
		applyAdd()
		// 关闭弹窗
		popup.value.close()
	}
	const formReset = (e) => {
		console.log('清空数据')
	}
</script>

<style lang="scss" scoped>
	.detail {
		background-color: #f5f5f5;
		width: 100%;
		height: calc(100vh - 160rpx);
		overflow-y: auto;

		.bgheader {

			height: 140rpx;
			// background-color: #505fff;
			background-color: #3975c6;

			.Info {
				height: 280rpx;
				background-color: #fff;
				border-radius: 16rpx;
				box-sizing: border-box;
				display: flex;
				box-shadow: 0 5px 5px -5px rgba(0, 0, 0, 0.4);

				.left {
					flex: 1.2;
					border-radius: 16rpx;
					overflow: hidden;
					position: relative;

					.type {
						position: absolute;
						top: 0;
						background-color: #494949;
						height: 30rpx;
						line-height: 30rpx;
						padding: 4rpx 13rpx;
						color: #fff;
						border-radius: 20rpx;
					}
				}

				.right {
					flex: 2;

					view:nth-child(1) {
						display: -webkit-box;
						/* 使用弹性盒子模型 */
						-webkit-box-orient: vertical;
						/* 设置子元素垂直排列 */
						overflow: hidden;
						/* 隐藏溢出内容 */
						-webkit-line-clamp: 1;
						/* 显示的行数 */
						text-overflow: ellipsis;
					}

					.slogan {

						display: -webkit-box;
						/* 使用弹性盒子模型 */
						-webkit-box-orient: vertical;
						/* 设置子元素垂直排列 */
						overflow: hidden;
						/* 隐藏溢出内容 */
						-webkit-line-clamp: 3;
						/* 显示的行数 */
						text-overflow: ellipsis;

					}

					.text {
						background-color: #fcf5ec;
						border-radius: 6rpx;
						box-sizing: border-box;



					}
				}
			}
		}

		.introduction {
			margin-top: 170rpx;
			background-color: #fff;

			.title {
				font-size: 32rpx;
			}

			.textInfo {
				line-height: 60rpx;
				font-size: 28rpx;
				font-family: PingFang SC;

			}
		}

		.requirements {
			background-color: #fff;

			.title {
				font-size: 32rpx;
			}

		}

		.volunteerList {
			box-sizing: border-box;
			background-color: #fff;

			.num {
				color: #616161;
				font-size: 24rpx;

				.organizationNum {
					color: #502de5;
					font-size: 26rpx;
					font-weight: bold;
				}
			}

			.person_img {
				display: grid;
				grid-template-columns: repeat(5, 1fr);
				gap: 10rpx;
				max-height: 400rpx;
				overflow-y: scroll;


				.item {
					font-size: 22rpx;

					.item_img {
						font-size: 32rpx;
						color: #fff;
						height: 80rpx;
						width: 80rpx;
						border-radius: 50%;
						overflow: hidden;
					}
				}
			}
		}

		.Application {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			// height: 100rpx;
			width: 100%;
			box-sizing: border-box;
			padding: 25rpx 40rpx;

			.btn {
				// height: 80rpx;
				border-radius: 80rpx;
				background-image: linear-gradient(#9ba3ff, #253bff);
				text-align: center;
				padding: 30rpx 10rpx;
				color: #fff;
				// line-height: 80rpx;
			}

			.expire-btn {
				padding: 28rpx 0;
				background-image: linear-gradient(#a3a3a3, #464646);
			}
		}

		.img {
			height: 100%;
			width: 100%;
			background-color: pink;
		}
	}

	::v-deep.uni-popup__wrapper {
		// 	width: 90%;
		border-radius: 12rpx;
	}

	.popup-content {
		width: 85vw;
		border-radius: 12rpx;

		.uni-input {
			background-color: #f5f5f5;
			height: 50rpx;
			border-radius: 8rpx;
		}

		.uni-input1 {
			background-color: #fff;
			height: 50rpx;
			border-radius: 8rpx;
		}

		.form_title {
			margin-bottom: 5rpx;


		}

		.require::before {
			content: '* ';
			color: #ff0212;
		}

		.select {
			padding-left: 0;
			height: 20rpx;
			box-sizing: border-box;
		}

		.btn {
			background-color: #fff;
			border: none !important;
			color: #6975ff;
		}

		.btn::after {
			// background-color: #fff;
			border: none !important;

		}


		.title {}

	}

	.uni-input-wrapper {
		.icon {
			right: 10rpx;
			top: 15rpx;
			color: #xe434;
		}
	}
</style>